<template>
  <div class="table-box">
    <ProTable ref="proTable" title="菜单列表" :request-api="getCheckinList" :columns="columns">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="Download" @click="downloadFile">导出签到数据</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="menuMange">
import { ref } from "vue";
import dayjs from "dayjs";
import { ElMessageBox, ElMessage } from "element-plus";
import { ColumnProps } from "@/components/ProTable/interface";
import { useDownload } from "@/hooks/useDownload";
import { Download } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { getCheckinList, pickGift } from "@/api/modules/checkinList";

const proTable = ref();

// 表格列定义
const columns: ColumnProps[] = [
  { prop: "userId", label: "用户ID" },
  { prop: "name", label: "用户姓名", search: { el: "input" } },
  { prop: "companyName", label: "公司名称", search: { el: "input" } },
  {
    prop: "checkinTime",
    label: "签到时间",
    search: {
      el: "date-picker",
      span: 2,
      props: {
        type: "daterange",
        valueFormat: "YYYY-MM-DD"
      },
      defaultValue: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")]
    }
  },
  {
    prop: "isPickGift",
    label: "是否领取礼物",
    enum: [
      { label: "是", value: "true" },
      { label: "否", value: "false" }
    ],
    search: { el: "select", props: { filterable: true } },
    render: ({ row }) => {
      // 兼容布尔或字符串
      const isPicked = row.isPickGift === true || row.isPickGift === "true";
      const checkinExpired = dayjs(row.checkinTime).isBefore(dayjs(), "day");

      const handleClick = async () => {
        if (isPicked) {
          ElMessage.warning(`用户「${row.name}」已领取过礼物！`);
          return;
        }
        if (checkinExpired) {
          ElMessage.warning(`用户「${row.name}」的签到记录已过期，无法领取礼物！`);
          return;
        }

        try {
          await pickGift({ checkinId: row.checkinId });
          ElMessage.success(`用户「${row.name}」成功领取礼物！`);
          row.isPickGift = true;
        } catch (err) {
          ElMessage.error("领取失败，请重试！");
        }
      };

      const renderButton = () => {
        if (isPicked) {
          return (
            <el-button type="info" size="small" disabled style={{ margin: "0 5px" }}>
              已领取
            </el-button>
          );
        }
        if (checkinExpired) {
          return (
            <el-button type="warning" size="small" disabled style={{ margin: "0 5px" }}>
              已过期
            </el-button>
          );
        }
        return (
          <el-button type="success" size="small" onClick={handleClick} style={{ margin: "0 5px" }}>
            领取礼物
          </el-button>
        );
      };

      return renderButton();
    }
  }
];

// 导出函数
const downloadFile = async () => {
  let obj = {
    ...proTable.value?.searchParam,
    pageNum: 1,
    pageSize: proTable.value?.pageable.total
  };
  console.log("导出参数：", obj);
  let { list } = await getCheckinList(obj);
  const tableData = list || [];

  const exportColumns = columns
    .filter((col): col is { prop: string; label: string } => !!col.prop && !!col.label)
    .map(col => ({ prop: col.prop, label: col.label }));

  ElMessageBox.confirm("确认导出签到记录数据？", "温馨提示", { type: "warning" }).then(() =>
    useDownload(tableData, "签到记录表", exportColumns)
  );
};
</script>
